package com.airconditioner.sales.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.airconditioner.sales.R;
import com.airconditioner.sales.model.RegisterInfo;
import com.airconditioner.sales.model.ResiterInfoResult;
import com.airconditioner.sales.util.CodeConfig;
import com.airconditioner.sales.util.MyCountDownTimer;
import com.airconditioner.sales.util.PrefName;
import com.airconditioner.sales.util.PreferencesUtils;
import com.airconditioner.sales.util.StringUtil;
import com.airconditioner.sales.util.Url;
import com.alibaba.fastjson.JSON;

import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：shuizi_wade on 2017/1/16 14:22
 * 邮箱：674618016@qq.com
 */
@ContentView(R.layout.activity_register)
public class RegisterActivity extends BaseActivity {
    @ViewInject(R.id.btn_register_code)
    Button btn_register_code;
    @ViewInject(R.id.iv_photo)
    ImageView iv_photo;
    private String path;
    @ViewInject((R.id.et_register_user_name))
    EditText et_name;
    @ViewInject((R.id.et_register_user_phone))
    EditText et_phone;
    @ViewInject((R.id.et_register_code))
    EditText et_code;
    private String phone, code, name;

    @Override
    public void init() {
        super.init();
        title_iv_back.setVisibility(View.INVISIBLE);
        title_relate_layout.setBackgroundColor(getResources().getColor(R.color.white_color));
        title_tv_title.setText(R.string.register);
    }


    @Event(value = {R.id.iv_photo, R.id.btn_register_code, R.id.btn_register})
    private void getEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_register_code:
                phone = et_phone.getText().toString();
                if (StringUtil.isBlank(phone)) {
                    senToa(getString(R.string.input_phone));
                    return;
                }
                if (phone.length() < 11) {
                    senToa(getString(R.string.input_correct_phone));
                    return;
                }
                MyCountDownTimer myCountDownTimer = new MyCountDownTimer(context, 60000, 1000, btn_register_code);
                btn_register_code.setBackgroundResource(R.drawable.btn_code_click);
                myCountDownTimer.start();
                break;
            case R.id.iv_photo:
//                Intent intent = new Intent();
//                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                intent.setAction(Intent.ACTION_GET_CONTENT);
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, CodeConfig.code_photo);
                break;
            case R.id.btn_register:
                phone = et_phone.getText().toString();
                name = et_name.getText().toString();
                code = et_code.getText().toString();
                if (StringUtil.isBlank(name)) {
                    senToa(getString(R.string.input_user_name));
                    return;
                }
                if (StringUtil.isBlank(phone)) {
                    senToa(getString(R.string.input_phone));
                    return;
                }
                if (phone.length() < 11) {
                    senToa(getString(R.string.input_correct_phone));
                    return;
                }
                if (StringUtil.isBlank(code)) {
                    senToa(getString(R.string.input_code));
                    return;
                }
                if (StringUtil.isBlank(path)) {
                    senToa(getString(R.string.add_pic));
                    return;
                }
                RequestParams params = new RequestParams(Url.COMMIT_USER_PIC);
//                params.setMultipart(true);
                params.setAsJsonContent(true);
                //创建List<KeyValue>对象
                List<KeyValue> list = new ArrayList<>();
                //给list中添加数据，filePah是上传的文件路径，比如sd卡中图片
                list.add(new KeyValue("payeePic", new File(path)));//文件流数据
                list.add(new KeyValue("mobile", phone));
                list.add(new KeyValue("wechatId", "wangjin111"));
                list.add(new KeyValue("salesName", name));
                list.add(new KeyValue("token", "ssss"));
                //创建MultipartBody
                MultipartBody body = new MultipartBody(list, "UTF-8");
                //添加请求参数
                params.setRequestBody(body);
                httpPost("register", params);
//                jumpActvity(HomeActivity.class);
                break;
        }
    }

    @Override
    public void success(String result, String type) {
        super.success(result, type);
        if (type.equals("register")) {
            ResiterInfoResult resiterInfoResult = JSON.parseObject(result, ResiterInfoResult.class);
            RegisterInfo registerInfo = resiterInfoResult.getResObj();
            PreferencesUtils.putString(context, PrefName.MOBILE, registerInfo.getMobile());
            PreferencesUtils.putString(context, PrefName.PAYEE_PIC, registerInfo.getPayeePic());
            PreferencesUtils.putString(context, PrefName.SALES_NAME, registerInfo.getSalesName());
            PreferencesUtils.putString(context, PrefName.WECHAT_ID, registerInfo.getWechatId());
            jumpActvity(HomeActivity.class);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CodeConfig.code_photo:
                    try {
                        Uri originalUri = data.getData();//获得图片的uri
//                        data.getData();
                        ContentResolver resolver = getContentResolver();
                        Bitmap bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                        //显得到bitmap图片
                        iv_photo.setImageBitmap(bm);
                        String[] filePathColumns = {MediaStore.Images.Media.DATA};
                        Cursor c = resolver.query(originalUri, filePathColumns, null, null, null);
                        int columnIndex = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        c.moveToFirst();
                        path = c.getString(columnIndex);
                        c.close();
                    } catch (IOException e) {
                        Log.e("TAG-->Error", e.toString());
                    }
                    break;
            }
        }
    }

    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public Uri getPictureUri(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }
}
